package com.gitee.cui.netty.protocol;

import com.gitee.cui.util.Logger;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * ProtoBuf序列化与反序列化构建器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/25 14:27
 **/
public class ProtoBufBuilder {

    public static MsgProtos.Msg buildMsg() {
        MsgProtos.Msg.Builder personBuilder = MsgProtos.Msg.newBuilder();
        personBuilder.setId(1000);
        personBuilder.setContent("测试字符串内容");
        MsgProtos.Msg msg = personBuilder.build();
        return msg;
    }

    @Test
    public void serAndDesr1Test() throws IOException {
        MsgProtos.Msg msg = buildMsg();
        // 将ProtoBuf对象序列化成二进制字节数组
        byte[] data = msg.toByteArray();
        // 可用于网络传输，保存到内存或外存
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(data);
        data = outputStream.toByteArray();
        // 二进制字节数组反序列化为ProtoBuf对象
        MsgProtos.Msg inMsg = MsgProtos.Msg.parseFrom(data);
        Logger.info("id= " + inMsg.getId());
        Logger.info("content= " + inMsg.getContent());
    }

    @Test
    public void serAndDesr2Test() throws IOException {
        MsgProtos.Msg msg = buildMsg();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        msg.writeTo(outputStream);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        // 从二进制码流反序列化成ProtoBuf对象
        MsgProtos.Msg parseFrom = MsgProtos.Msg.parseFrom(inputStream);
        Logger.info("id= " + parseFrom.getId());
        Logger.info("content= "+ parseFrom.getContent());
    }

    @Test
    public void serAndDesr3Test() throws IOException {
        MsgProtos.Msg msg = buildMsg();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        msg.writeTo(outputStream);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        // 从二进制码流反序列化成ProtoBuf对象
        MsgProtos.Msg parseFrom = MsgProtos.Msg.parseDelimitedFrom(inputStream);
        Logger.info("id= " + parseFrom.getId());
        Logger.info("content= "+ parseFrom.getContent());
    }
}
